package com.pay.bean;

import com.pay.alipay.util.AlipayNotify;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 支付宝同步支付结果对象。
 * 详情见：https://docs.open.alipay.com/62/103566
 * Created by ThreeManTeam on 2016/11/20.
 */

@Getter
@Setter
public class AliPayResult implements Serializable {

    private Long originPayNotifyId;

    /**
     * 调用是否成功?
     */
    private boolean reqSuccess = false;
    /**
     * 校验是否成功？
     */
    private boolean verifySuccess = false;

    private String outTradeNo;

    private String subject;

    private String paymentType;

    private String exterface = "create_direct_pay_by_user";

    private String tradeNo;

    private String tradeStatus;

    private String notifyId;

    private Date notifyTime = null;

    private String notifyType;

    private String sellerEmail;

    private String sellerId;

    private String buyerEmail;

    private String buyerId;

    private BigDecimal totalFee = BigDecimal.ZERO;

    private String body;

    private String extraCommonParam;

    public void initialEx(Map<String, String> params, String partnerId, String aliPublicKey) {
        _initial(params, partnerId, aliPublicKey);
    }

    public Map<String, String> initial(Map<String, String[]> notifyParams, String partnerId, String aliPublicKey) {
        Map<String, String> params = new HashMap<>();
        notifyParams.keySet().forEach(x -> {
            String[] value = notifyParams.get(x);
            Optional<String> optional = Arrays.stream(value).reduce((t, y) -> t += ("," + y));
            params.put(x, optional.orElse(""));
        });
        _initial(params, partnerId, aliPublicKey);
        return params;
    }

    private void _initial(Map<String, String> params, String partnerId, String aliPublicKey) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //调用是否成功？
            if (params.containsKey("is_success")) {
                setReqSuccess("T".equals(params.get("is_success")));
            }

            //校验是否成功？
            boolean verify_result = AlipayNotify.verify(params, partnerId, aliPublicKey);
            setVerifySuccess(verify_result);

            if (verify_result) {
                if (params.containsKey("out_trade_no"))
                    setOutTradeNo(params.get("out_trade_no"));

                if (params.containsKey("payment_type"))
                    setPaymentType(params.get("payment_type"));

                if (params.containsKey("exterface"))
                    setExterface(params.get("exterface"));

                if (params.containsKey("trade_no"))
                    setTradeNo(params.get("trade_no"));

                if (params.containsKey("trade_status")) {
                    String status = params.get("trade_status");
                    setTradeStatus(status);
                    if (!isReqSuccess())
                        setReqSuccess(TradeState.TRADE_SUCCESS.name().equalsIgnoreCase(status));
                }

                if (params.containsKey("notify_id"))
                    setNotifyId(params.get("notify_id"));

                if (params.containsKey("notify_type"))
                    setNotifyType(params.get("notify_type"));
                if (params.containsKey("notify_time"))
                    setNotifyTime(sdf.parse(params.get("notify_time")));

                if (params.containsKey("seller_email"))
                    setSellerEmail(params.get("seller_email"));
                if (params.containsKey("seller_id"))
                    setSellerId(params.get("seller_id"));
                if (params.containsKey("buyer_email"))
                    setBuyerEmail(params.get("buyer_email"));
                if (params.containsKey("buyer_id"))
                    setBuyerId(params.get("buyer_id"));

                if (params.containsKey("total_fee")) {
                    if (params.get("total_fee") != null && params.get("total_fee").length() > 0) {
                        setTotalFee(new BigDecimal(params.get("total_fee")).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                } else if (params.containsKey("total_amount")) {
                    if (params.get("total_amount") != null && params.get("total_amount").length() > 0) {
                        setTotalFee(new BigDecimal(params.get("total_amount")).setScale(2, BigDecimal.ROUND_HALF_UP));
                    }
                }

                if (params.containsKey("body"))
                    setBody(params.get("body"));

                if (params.containsKey("extra_common_param"))
                    setExtraCommonParam(params.get("extra_common_param"));

                if (params.containsKey("subject"))
                    setSubject(new String(params.get("subject").getBytes("ISO-8859-1"), "UTF-8"));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
